package com.gpc.hexapods.activity;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.gpc.hexapods.R;
import com.gpc.hexapods.adapter.AutoListAdapter;
import com.gpc.hexapods.adapter.GridButtonAdapter;
import com.gpc.hexapods.adapter.SeekBarListAdapter;
import com.gpc.hexapods.data.Cons;
import com.gpc.hexapods.data.SeekInfo;
import com.gpc.hexapods.gl.GLView;
import com.gpc.hexapods.gl.GlListener;
import com.gpc.hexapods.layer.ControlLayout;
import com.gpc.hexapods.service.BluetoothChatService;
import com.gpc.hexapods.utils.Utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * This is the main Activity that displays the current chat session.
 */
public class BluetoothChat extends Activity implements GridButtonAdapter.ButtonOnClickListener,
        SeekBarListAdapter.SeekBarChangeListener, AutoListAdapter.AutoChangeListener, GlListener {
    // Debugging
    private static final String TAG = "BluetoothChat";
    private static final boolean D = true;

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };

    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    // Key names received from the BluetoothChatService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;

    // Layout Views
//    private TextView mTitle;
    private GLView mGLView;
    private ListView mConversationView;
    private EditText mOutEditText;
    private Button mSendButton;
    private Button mResetButton;
    private Button mPowerButton;
    private Button mClearButton;
    private Button mUpdateButton;
    private GridView mGridViewButton;
    private ListView mLeftListView;
    private ListView mRightListView;
    private ListView mHeadListView;
    private SeekBarListAdapter mLeftListAdapter;
    private SeekBarListAdapter mRightListAdapter;
    private SeekBarListAdapter mHeadListAdapter;
    private ControlLayout mControlLayout;
    private int mCmd;
    private Map<String, Integer> mHexMap;

    // Name of the connected device
    private String mConnectedDeviceName = null;
    // Array adapter for the conversation thread
    private ArrayAdapter<String> mConversationArrayAdapter;
    // String buffer for outgoing messages
    private StringBuffer mOutStringBuffer;
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the chat services
    private BluetoothChatService mChatService = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(D) Log.e(TAG, "+++ ON CREATE +++");

        // Set up the window layout
        setContentView(R.layout.main);

        // Set up the custom title
        setTitle(R.string.app_name);
        initView();
        initData();
        requestPermission();

        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        // Otherwise, setup the chat session
        } else {
            if (mChatService == null) setupChat();
        }
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        if(D) Log.e(TAG, "+ ON RESUME +");

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
              // Start the Bluetooth chat services
              mChatService.start();
            }
        }
    }

    private void initView() {
        mControlLayout = findViewById(R.id.control_layout);
        mGLView = (GLView) findViewById(R.id.glView);
        mGLView.setListener(this);
        mControlLayout.setCtrlListener(mGLView);
    }
    
    private void initData() {
        mHexMap = Utils.getHexMap();

        List<SeekInfo> leftInfos = new ArrayList<>();
        leftInfos.add(new SeekInfo("L11", Cons.L11));
        leftInfos.add(new SeekInfo("L12", Cons.L12));
        leftInfos.add(new SeekInfo("L13", Cons.L13));
        leftInfos.add(new SeekInfo("L21", Cons.L21));
        leftInfos.add(new SeekInfo("L22", Cons.L22));
        leftInfos.add(new SeekInfo("L23", Cons.L23));
        leftInfos.add(new SeekInfo("L31", Cons.L31));
        leftInfos.add(new SeekInfo("L32", Cons.L32));
        leftInfos.add(new SeekInfo("L33", Cons.L33));
        mLeftListAdapter = new SeekBarListAdapter(this, this, leftInfos, 0);

        List<SeekInfo> rightInfos = new ArrayList<>();
        rightInfos.add(new SeekInfo("R11", Cons.R11));
        rightInfos.add(new SeekInfo("R12", Cons.R12));
        rightInfos.add(new SeekInfo("R13", Cons.R13));
        rightInfos.add(new SeekInfo("R21", Cons.R21));
        rightInfos.add(new SeekInfo("R22", Cons.R22));
        rightInfos.add(new SeekInfo("R23", Cons.R23));
        rightInfos.add(new SeekInfo("R31", Cons.R31));
        rightInfos.add(new SeekInfo("R32", Cons.R32));
        rightInfos.add(new SeekInfo("R33", Cons.R33));
        mRightListAdapter = new SeekBarListAdapter(this, this, rightInfos, 1);

        List<SeekInfo> headInfos = new ArrayList<>();
        headInfos.add(new SeekInfo("HD1", Cons.HD1));
        headInfos.add(new SeekInfo("HD2", Cons.HD2));
        mHeadListAdapter = new SeekBarListAdapter(this, this, headInfos, 2);
    }
    
    private void setupChat() {
        Log.d(TAG, "setupChat()");
        // Initialize the array adapter for the conversation thread
        mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
        mConversationView = (ListView) findViewById(R.id.in);
        mConversationView.setAdapter(mConversationArrayAdapter);
        mConversationArrayAdapter.add(" ");

        // Initialize the compose field with a listener for the return key
        mOutEditText = (EditText) findViewById(R.id.edit_text_out);
        mOutEditText.setOnEditorActionListener(mWriteListener);

        // Initialize the send button with a listener that for click events
        mSendButton = (Button) findViewById(R.id.button_send);
        mClearButton = (Button) findViewById(R.id.button_clear);
        mPowerButton = (Button) findViewById(R.id.button_power);
        mResetButton = (Button) findViewById(R.id.button_reset);
        mUpdateButton = (Button) findViewById(R.id.button_update);
        
        mSendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Send a message using content of the edit text widget
                TextView view = (TextView) findViewById(R.id.edit_text_out);
                String message = view.getText().toString();
                if (message.startsWith("~")) {
                    try {
                        /*int cmd = Integer.valueOf(message.substring(1, 3));
                        cmd = cmd / 10 * 16 + cmd % 10;
                        int value = Integer.valueOf(message.substring(3, 5));
                        value = value / 10 * 16 + value % 10;*/

                        int a = mHexMap.get(message.substring(1, 2));
                        int b = mHexMap.get(message.substring(2, 3));
                        int c = mHexMap.get(message.substring(3, 4));
                        int d = mHexMap.get(message.substring(4, 5));

                        int cmd = a * 16 + b;
                        int value = c * 16 + d;

                        sendMessageToREAL(cmd, value);
                    } catch (Exception e) {
                    }
                } else {
//                    sendMessage(message);
                    byte[] send = (message + "\r\n").getBytes();
                    byte[] msg = new byte[send.length + 3];
                    msg[0] = (byte) 0xfc;
                    msg[send.length + 1] = (byte) 0xfd;
                    msg[send.length + 2] = (byte) 0xfe;
                    System.arraycopy(send, 0, msg, 1, send.length);
                    Log.i(TAG, "send : " + Arrays.toString(msg));
                    mChatService.write(msg);
                }
            }
        });
        
        mClearButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mConversationArrayAdapter.clear();
            }
        });
        
        mPowerButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				sendMessageToREAL(0x71, 1);
			}
		});
        
        mResetButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				initData();
                mLeftListView.setAdapter(mLeftListAdapter);
                mRightListView.setAdapter(mRightListAdapter);
                mHeadListView.setAdapter(mHeadListAdapter);
				sendMessageToREAL(0x81, 0);
			}
		});

        mUpdateButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                sendFile("/sdcard/Robot.bin");
            }
        });
        
        mGridViewButton = (GridView) findViewById(R.id.gridview_button);
        List<String> buttonList = new ArrayList<String>();
        buttonList.add("LF");
        buttonList.add("RF");
        buttonList.add("LB");
        buttonList.add("RB");
        buttonList.add("HD");
        GridButtonAdapter mGridButtonAdapter = new GridButtonAdapter(BluetoothChat.this, BluetoothChat.this, buttonList);
        mGridViewButton.setAdapter(mGridButtonAdapter);
        mGridViewButton.setVisibility(View.GONE);

        mLeftListView = (ListView) findViewById(R.id.hand_listview);
        mRightListView = (ListView) findViewById(R.id.leg_listview);
        mHeadListView = (ListView) findViewById(R.id.head_listview);

        mLeftListView.setAdapter(mLeftListAdapter);
        mRightListView.setAdapter(mRightListAdapter);
        mHeadListView.setAdapter(mHeadListAdapter);

        // Initialize the BluetoothChatService to perform bluetooth connections
        mChatService = new BluetoothChatService(this, mHandler);

        // Initialize the buffer for outgoing messages
        mOutStringBuffer = new StringBuffer("");
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
        }
    }

    @Override
    public void onClickListener(int position) {
    	mCmd = (mCmd & 0x0f) | (position << 4);
    }
    
    @Override
    public void changeListener(int position, int value) {
        if (position > 18) {
            mCmd = 0x90 | (position - 18);
        } else if (position > 15) {
            mCmd = 0x60 | (position - 15);
        } else if (position > 12) {
            mCmd = 0x50 | (position - 12);
        } else if (position > 9) {
    		mCmd = 0x40 | (position - 9);
    	} else if (position > 6) {
    		mCmd = 0x30 | (position - 6);
    	} else if (position > 3) {
            mCmd = 0x20 | (position - 3);
        } else {
            mCmd = 0x10 | position;
        }
    	
//    	mCmd = (mCmd & 0xf0) | position;
    	sendMessageToREAL(mCmd, value);
//        byte[] send = new byte[1];
//        send[0] = (byte) value;
//        mChatService.write(send);
    }

    @Override
    public void autoListener(int position, int val) {
        //sendMessageToREAL((0x80 | position) + 1, val);
        byte[] send = new byte[1];
        send[0] = (byte) val;
        mChatService.write(send);
    }

    @Override
    public void sendArray(short[] value) {
        byte cmd = (byte) 0xA0;
        Log.i(TAG, "sendArray -> input : " + Arrays.toString(value));
        byte[] array = Utils.shortToByte(value);
        //Log.i(TAG, "sendArray -> output : " + Arrays.toString(array));
        int[] temp = new int[array.length];
        for (int i = 0; i < array.length; i++) {
            temp[i] = array[i] & 0xFF;
        }
        Log.i(TAG, "sendArray -> output : " + Arrays.toString(temp));
        int size = array.length + 5;
        byte[] send = new byte[size];
        send[0] = (byte) 0xFF;
        send[1] = (byte) cmd;
        System.arraycopy(array, 0, send, 2, array.length);
        send[size - 3] = Utils.crc(send);
        send[size - 2] = (byte) 0xFD;
        send[size - 1] = (byte) 0xFE;
        //Log.i(TAG, "sendArray -> send : " + Arrays.toString(send));
        int[] end = new int[send.length];
        String[] list = new String[send.length];
        for (int i = 0; i < send.length; i++) {
            end[i] = send[i] & 0xFF;
            list[i] = Integer.toHexString(end[i]);
        }
        Log.i(TAG, "sendArray -> send : " + Arrays.toString(end));
        Log.i(TAG, "sendArray -> list : " + Arrays.toString(list));
        mChatService.write(send);
    }

    private void delay(int time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void sendMessageToREAL(int cmd, int value) {
    	byte[] send = new byte[6];
    	send[0] = (byte) 0xFF;
    	send[1] = (byte) cmd;
    	send[2] = (byte) value;
    	send[3] = Utils.crc(send);
    	send[4] = (byte) 0xFD;
    	send[5] = (byte) 0xFE;
		mChatService.write(send);
    }

    private void sendFile(String fileName) {
        File file = new File(fileName);
        if (!file.isFile()) {
            Log.e(TAG, fileName + " is no File");
            return;
        }

        int length = (int) file.length();
        byte[] buf = new byte[length];

        Log.e(TAG, fileName + " is File, length : " + length);
        try {
            FileInputStream is = new FileInputStream(fileName);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int len = 0;
            while ((len = is.read(buf)) != -1) {
                os.write(buf, 0, len);
            }
            is.close();
            os.close();
        } catch (Exception e) {
            Log.e(TAG, "sendFile Exception : " + e.toString());
            return;
        }

        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }
        mChatService.write(buf);
        mConversationArrayAdapter.add("write length --> " + length);
    }
    
    @Override
    public synchronized void onPause() {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
    }

    @Override
    public void onStop() {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mGLView.setListener(null);
        // Stop the Bluetooth chat services
        if (mChatService != null) mChatService.stop();
        if(D) Log.e(TAG, "--- ON DESTROY ---");
    }

    private void ensureDiscoverable() {
        if(D) Log.d(TAG, "ensure discoverable");
        if (mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    /**
     * Sends a message.
     * @param message  A string of text to send.
     */
    private void sendMessage(String message) {
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }

        // Check that there's actually something to send
        if (message.length() > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
            byte[] send = message.getBytes();
            mChatService.write(send);

            // Reset out string buffer to zero and clear the edit text field
            mOutStringBuffer.setLength(0);
            mOutEditText.setText(mOutStringBuffer);
        }
    }

    // The action listener for the EditText widget, to listen for the return key
    private TextView.OnEditorActionListener mWriteListener =
        new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            // If the action is a key-up event on the return key, send the message
            if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
                String message = view.getText().toString();
                sendMessage(message);
            }
            if(D) Log.i(TAG, "END onEditorAction");
            return true;
        }
    };

    // The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                case BluetoothChatService.STATE_CONNECTED:
                    setTitle(getString(R.string.title_connected_to) + mConnectedDeviceName);
                    mConversationArrayAdapter.clear();
                    break;
                case BluetoothChatService.STATE_CONNECTING:
                	setTitle(R.string.title_connecting);
                    break;
                case BluetoothChatService.STATE_LISTEN:
                case BluetoothChatService.STATE_NONE:
                	setTitle(R.string.title_not_connected);
                    break;
                }
                break;
            case MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                // construct a string from the buffer
                String writeMessage = new String(writeBuf);
//                mConversationArrayAdapter.add("Me:  " + writeMessage);
                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg1);
                mConversationArrayAdapter.add(/*mConnectedDeviceName+":  " + */readMessage);
                break;
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(D) Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                // Get the device MAC address
                String address = data.getExtras()
                                     .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                // Get the BLuetoothDevice object
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                // Attempt to connect to the device
                mChatService.connect(device);
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
                setupChat();
            } else {
                // User did not enable Bluetooth or an error occured
                Log.d(TAG, "BT not enabled");
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.scan:
        	if (mChatService != null 
        		&& mChatService.getState() == BluetoothChatService.STATE_CONNECTED) {
        		mChatService.stop();
        	} else {
	            // Launch the DeviceListActivity to see devices and do scan
	            Intent serverIntent = new Intent(this, DeviceListActivity.class);
	            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
        	}
            return true;

//        case R.id.discoverable:
//            // Ensure this device is discoverable by others
//            ensureDiscoverable();
//            return true;

        case R.id.left:
            if (mLeftListView.getVisibility() == View.VISIBLE) {
                mLeftListView.setVisibility(View.GONE);
            } else {
                mLeftListView.setVisibility(View.VISIBLE);
                mRightListView.setVisibility(View.GONE);
                mHeadListView.setVisibility(View.GONE);
            }
            return true;

        case R.id.right:
            if (mRightListView.getVisibility() == View.VISIBLE) {
            	mRightListView.setVisibility(View.GONE);
            } else {
            	mRightListView.setVisibility(View.VISIBLE);
                mLeftListView.setVisibility(View.GONE);
                mHeadListView.setVisibility(View.GONE);
            }
            return true;

        case R.id.head:
            if (mHeadListView.getVisibility() == View.VISIBLE) {
                mHeadListView.setVisibility(View.GONE);
            } else {
                mHeadListView.setVisibility(View.VISIBLE);
                mRightListView.setVisibility(View.GONE);
                mLeftListView.setVisibility(View.GONE);
            }
            return true;
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        Log.i(TAG, "onRequest -> requestCode : " + requestCode + ", permissions : " + Arrays.toString(permissions)
                + ", grantResults : " + Arrays.toString(grantResults));
    }
}